import React from 'react';
import { Modal, Input, Table, Card, Button, message } from 'antd';
import { PlusOutlined, CloseCircleOutlined } from '@ant-design/icons';
export default function EditMemorandum(props) {
  const { hasEdit, sethasEdit, list, setList } = props;

  const columns = [
    {
      title: 'ID',
      dataIndex: 'memorandumId',
      key: 'memorandumId',
    },
    {
      title: 'memorandum Txt',
      key: 'txt',
      render: (n, index) => (
        <Input
          key={index}
          value={n.txt}
          onChange={(e) =>
            setList({
              ...list,
              memorandum: list.memorandum.map((i) => ({
                ...i,
                txt: i.memorandumId === n.memorandumId ? e.target.value : i.txt,
              })),
            })
          }
        />
      ),
    },
    {
      title: 'operation',
      render: (n) => (
        <Button
          key={n.memorandumId}
          icon={<CloseCircleOutlined spin />}
          onClick={() => handleItem(n.memorandumId)}
        />
      ),
    },
  ];

  const handleItem = (index) => {
    let data = JSON.parse(JSON.stringify(list));
    if (typeof index === 'number') {
      data.memorandum = data.memorandum.filter((i) => i.memorandumId !== index);
      message.warning('You deleted a memo！');
    } else {
      data.memorandum.push({
        memorandumId: Date.now(),
        txt: '',
      });
      message.success('You added a memo!');
    }
    setList(data);
  };

  return (
    <Modal
      title={
        <>
          <span style={{ marginRight: 20 }}>Edit Modal</span>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleItem} />
        </>
      }
      width={800}
      destroyOnClose
      visible={hasEdit}
      keyboard
      maskClosable
      onCancel={() => sethasEdit(false)}
      footer={[
        <Button key="back" onClick={() => sethasEdit(false)}>
          OK
        </Button>,
      ]}
    >
      <Card>
        <Table
          dataSource={
            !!list.memorandum &&
            list.memorandum.map((n, i) => ({ ...n, key: i + 1 }))
          }
          columns={columns}
          align="center"
          pagination={false}
          size="small"
          bordered
        />
      </Card>
    </Modal>
  );
}
